package com.xy.novelweb.controller;

import com.xy.novelweb.domain.Novel;
import com.xy.novelweb.service.SearchService;
import com.xy.novelweb.utils.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import redis.clients.jedis.Jedis;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("search")
@Controller
@Slf4j
public class SearchController {
		@Autowired
		private SearchService searchService;
	
		@RequestMapping(path = "searchbookname")
		public String searchBookByName (String bookname, HttpServletRequest request) {
				List<Novel> novels = searchService.searchBookByName(bookname);
				Jedis jedis = JedisUtil.getConnect();
				String reader = request.getRemoteHost();
				String key = "search:"+reader;
				String result = "result";
				try {
						if (jedis.exists(key)) {
								request.setAttribute("erro",true);
								request.setAttribute("searchresult", "result_erro");
								request.setAttribute("time",jedis.ttl(key));
								return "static/result_erro";
						}else {
								jedis.setex(key,20,reader);
								request.setAttribute("erro",false);
								request.setAttribute("authnameresult", "");
								request.setAttribute("booknameresult", bookname);
								request.setAttribute("searchresult", novels);
						}
				}catch (Exception e){
						log.error("错误消息：{}",e.getMessage(),e);
				}finally {
						JedisUtil.close(jedis);
				}
				log.info("searchBookByName:"+result);
				return "result";
		}

		@RequestMapping("searchauthname")
		public String searchAuthName (String authname, HttpServletRequest request) {
				List<Novel> novels = searchService.searchBookByAuth(authname);
				Jedis jedis = JedisUtil.getConnect();
				String auth = request.getRemoteHost();
				String key = "search:"+auth;
				try {
						if (jedis.exists(key)) {
								request.setAttribute("erro",true);
								request.setAttribute("searchresult", "result_erro");
								return "static/result_erro";
						}else {
								jedis.setex(key,20,auth);
								request.setAttribute("erro",false);
								request.setAttribute("booknameresult", "");
								request.setAttribute("authnameresult", authname);
								request.setAttribute("searchresult", novels);
						}
				}catch (Exception e){
						log.error("错误消息：{}",e.getMessage(),e);
				}finally {
						JedisUtil.close(jedis);
				}
				return "result";
		}
}
